/*
 * #%L
 * java model
 * %%
 * Copyright (C) 2009 - 2011 Stefan Isele
 * %%
 * All Rights Reserved.
 * This program is dual-licensed under the GNU General Public license
 * or a commercial license.
 * You may select to use one or the other of these licenses.
 * To obtain a commercial license please contact Stefan Isele at www.stefan-isele.de
 * Any modifications to this file must keep this entire header intact.
 * Redistribution, except as permitted by the selected license, is prohibited.
 * #L%
 */
package com.prefabware.jmodel.code.hash;

import com.prefabware.jmodel.JType;
import com.prefabware.jmodel.code.JCodeOptions;
import com.prefabware.jmodel.expression.JExpression;
import com.prefabware.jmodel.expression.JVariable;
import com.prefabware.jmodel.expression.JVariableBase;

/**
 * to create implementation of {@link Object#hashCode()}
 * use {@link #create(JVariableBase)} to create an instance
 * @author Stefan Isele
 * 
 */
public class HashCode {
	private JVariable variable;

	/**
	 * 
	 * @param variable
	 * @return a HashCode
	 */
	public static HashCode create(JVariable variable) {
		JType type = variable.getDeclaration().getType();
		if (type.equalsClass(boolean.class)) {
			return new HashCodeboolean(variable);
		} else if (type.equalsClass(double.class)) {
			return new HashCodedouble(variable);
		} else if (type.equalsClass(float.class)) {
			return new HashCodefloat(variable);
		} else if (type.equalsClass(long.class)) {
			return new HashCodelong(variable);
		} else if (type.equalsClass(int.class)) {
			return new HashCodeint(variable);
		} else
			return new HashCode(variable);
	};

	/**
	 * for internal use only,
	 * call {@link #create(JVariableBase)} for a new instance
	 * @param variable
	 */
	protected HashCode(JVariable variable) {
		super();
		this.variable = variable;
	}

	public JExpression getHashCode() {
		JExpression expression = new JExpression() {

			@Override
			public String asCode(JCodeOptions options) {
				String field = variable.asCode(JCodeOptions.SIMPLE_NAMES);
				return "((" + field + " == null) ? 0 : " + field + ".hashCode())";
			}
		};
		return expression;
	}

	public JVariable getVariable() {
		return variable;
	}
}
